package coder.nav.service;

import cn.hutool.core.bean.BeanUtil;
import coder.nav.model.NavUser;
import coder.nav.model.bo.NavLoginBO;
import coder.nav.model.vo.NavLoginVO;
import coder.nav.model.vo.NavUserVO;
import coder.nav.utils.JwtUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class NavLoginService {

    @Autowired
    private NavUserService userService;

    /**
     * 登录
     * @param loginBO 入参
     */
    public NavLoginVO login(NavLoginBO loginBO) {
        NavUser userInfo = userService.getByToken(loginBO.getToken());
        String token = loginBO.getToken();
        if(Objects.isNull(userInfo)) {
            userInfo = userService.getByUsernameAndPassword(loginBO.getUsername(), loginBO.getPassword());
            if(ObjectUtils.isEmpty(userInfo)) {
                throw new RuntimeException("用户名或密码错误");
            }
            token = JwtUtils.sign(userInfo.getId());
        }
        NavLoginVO vo = new NavLoginVO();
        vo.setToken(token);
        vo.setUserInfo(BeanUtil.copyProperties(userInfo, NavUserVO.class));
        return vo;
    }

    /**
     * 退出登录
     */
    public Boolean logout(String token) {
        return JwtUtils.cleanToken(token);
    }

    /**
     * 检查token
     * @param token 需要检查的token
     */
    public Boolean checkToken(String token) {
        return JwtUtils.checkToken(token);
    }

}
